﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CustomControls
{
    public class SelectAllTextBox : TextBox
    {

        public SelectAllTextBox()
        {
            /// Take largely from 
            /// http://www.intertech.com/Blog/post/How-to-Select-All-Text-in-a-WPF-Content-on-Focus.aspx
            EventManager.RegisterClassHandler(typeof(SelectAllTextBox), UIElement.PreviewMouseLeftButtonDownEvent,
                new MouseButtonEventHandler(SelectivelyHandleMouseButton), true);
            EventManager.RegisterClassHandler(typeof(SelectAllTextBox), UIElement.GotKeyboardFocusEvent,
                new RoutedEventHandler(SelectAllText), true);
            ///
        }


        /// <summary>
        /// Take largely from 
        /// http://www.intertech.com/Blog/post/How-to-Select-All-Text-in-a-WPF-Content-on-Focus.aspx
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void SelectivelyHandleMouseButton(object sender, MouseButtonEventArgs e)
        {
            var textbox = (sender as TextBox);
            if (textbox != null && !textbox.IsKeyboardFocusWithin)
            {
                if (e.OriginalSource.GetType().Name == "TextBoxView")
                {
                    e.Handled = true;
                    textbox.Focus();
                }
            }
        }

        /// <summary>
        /// Take largely from 
        /// http://www.intertech.com/Blog/post/How-to-Select-All-Text-in-a-WPF-Content-on-Focus.aspx
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void SelectAllText(object sender, RoutedEventArgs e)
        {
            var textBox = e.OriginalSource as TextBox;
            if (textBox != null)
                textBox.SelectAll();
        }

    }
}
